/******************************************************************
 * Created by: Goh Chee Hong                                    
 * Date of Creation:
 * Date of last modification: 31st/Jan/2009
 * Status: Finished.
 *                                                                
 * Description: a form that shows the feed details                        
 * ...
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

using System.Collections;
using Pbdms.BusinessLogic;
using Pbdms.NetworkDealer;
using Pbdms.Common.DataObject;
using Pbdms.BusinessLogic.FileTransfer;

namespace Pbdms.Forms.Views
{
    public partial class FrmViewAnItem : Form
    {
        private Buddy buddy = null;
        private string itemID="";
        private AuthTcpClient authClient;
        ResultItem item = null;
        public delegate void DelegateWorker(object sender);
        public FrmViewAnItem()
        {
                  
            InitializeComponent();
            customizeGridView();
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0; 
            this.FormClosing+=new FormClosingEventHandler(FrmViewAnItem_FormClosing);
        }
        /// <summary>
        /// set the parameters
        /// </summary>
        /// <param name="buddy"></param>
        /// <param name="itemID"></param>
        public void setParameters(Buddy buddy, string itemID)
        {
            this.buddy = buddy;
            this.itemID = itemID;
            clearItemInfo();
            if (authClient != null)
            {
                authClient.Close();
            }
   
        }
 
        /// <summary>
        /// clear all items
        /// </summary>
        private void clearItemInfo()
        {
            //clear all
            chkBShare.Checked = false;
            
            tbSummary.Text = "";
            tbPros.Text = "";
            tbCons.Text = "";
            tbTag.Text = "";
            mtbRating.Text = "0.0";
            tbReviewFile.Text = "";
            tbFileLocation.Text = "";
            lblFileSize.Text = "N/A";
            lblFileExistence.Text = "N/A";
            
            chkBShare.Checked = false;
            if (grdvItem.Rows.Count != 0)
            {
                grdvItem.DataSource = null;
            }
            tbSummary.ReadOnly = true;
            tbPros.ReadOnly = true ;
            tbCons.ReadOnly=true ;
            tbTag.ReadOnly=true;
            mtbRating.ReadOnly=true;
            tbReviewFile.ReadOnly=true;
            tbFileLocation.ReadOnly=true;
           
         

        }
        /// <summary>
        /// customize the gridview, column by column
        /// </summary>
        private void customizeGridView()
        {
            DataTable dt = new DataTable();
            //add 10 columns
            for (int i = 0; i < 9; i++)
            {
                dt.Columns.Add();
            }
            grdvItem.DataSource = dt;
            
            for (int i = 0; i < 9; i++)
            {
                switch (i)
                {
                        

                    case 1: grdvItem.Columns[0].HeaderText = "Title"; grdvItem.Columns[0].Width = 200; break;
                    case 2: grdvItem.Columns[1].HeaderText = "Author"; grdvItem.Columns[1].Width = 150; break;
                    case 3: grdvItem.Columns[2].HeaderText = "Publisher"; grdvItem.Columns[2].Width = 100; break;
                    case 4: grdvItem.Columns[3].HeaderText = "Year"; grdvItem.Columns[3].Width = 50; break;
                    case 5: grdvItem.Columns[4].HeaderText = "Edition"; grdvItem.Columns[4].Width = 50; break;
                    case 6: grdvItem.Columns[5].HeaderText = "Pages"; grdvItem.Columns[5].Width = 50; break;
                    case 7: grdvItem.Columns[6].HeaderText = "Editor"; grdvItem.Columns[6].Width = 100; break;
                    case 8: grdvItem.Columns[7].HeaderText = "Organization"; grdvItem.Columns[7].Width = 100; break;
                    case 9: grdvItem.Columns[8].HeaderText = "Volume"; grdvItem.Columns[8].Width = 50; break;

                }

            }
        }
        
        //report progress of downloading
        private void setProgress(object sender,string perc)
        {
            try
            {
                if (InvokeRequired)
                {

                 
                }
                else
                {
                    progressBar1.Value = int.Parse(perc);
                }
            }
            catch
            {
                
            }

        }
        /// <summary>
        /// start 
        /// </summary>
        public void Start()
        {
            Thread thStart = new Thread(new ThreadStart(Download));
            thStart.IsBackground = true;
            thStart.Start();
        }
        /// <summary>
        /// download method
        /// </summary>
        private void Download()
        {
            try
            {
                 // connect method
                authClient = new AuthTcpClient(buddy.IpAdd, NetworkDealer.NetworkDealer.LISTEN_PORT, buddy.KeyID, Program.keyControl, Program.publicKeyControl, Program.friendControl);
                authClient.Connect();
                if (authClient.IsAuthenticated() == false)
                {
                    throw new Exception();
                }
                NetworkMessage message = new NetworkMessage();
                message.TypeOfMessage = NetworkDealer.NetworkDealer.VIEWITEM_REQUEST;

                message.MessageContent = itemID;
                authClient.sendMessage(message);
                //receive viewitem reply
                message = authClient.receiveMessage();
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ResultItem));
                //deserialize
                System.IO.StringReader strReader = new System.IO.StringReader(message.MessageContent);
                item = (ResultItem)serializer.Deserialize(strReader);
                finishedDownloading(null);
            }
            catch
            {
                if (authClient != null)
                {
                    authClient.Close();
                }
            }
        }
        /// <summary>
        /// cancel method
        /// </summary>
        public void Cancel()
        {
            if (authClient != null)
            {
                authClient.Close();
            }
        }
     
        //form closing event
        private void FrmViewAnItem_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;

            this.Hide();
           

        }
        //Finiished downloading
        private void finishedDownloading(object sender)
        {
          
            try
            {
                if (this.InvokeRequired)
                {

                    DelegateWorker deleGateWorker = new DelegateWorker(finishedDownloading);
                    this.Invoke(deleGateWorker, new object[] {null});
                }
                else
                {
                 
                   //loadItem(item);
                    loadItem();
                }
            }
            catch
            {
            }
           
        }
        /// <summary>
        /// Download button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateInfo_Click(object sender, EventArgs e)
        {
            if (item == null)
            {
                return;
            }
            Pbdms.Forms.Tools.FrmLibraryTransfer libraryTransfer = new Pbdms.Forms.Tools.FrmLibraryTransfer();

            libraryTransfer.setResultItem(item);
            System.Windows.Forms.DialogResult disResult = libraryTransfer.ShowDialog();
            //if copying is completed successfully
            if (disResult == System.Windows.Forms.DialogResult.OK)
            {
                grdvItem.SelectedRows[0].Tag = libraryTransfer.getItem();
                BusinessLogic.ItemSynchronizer.AppendNewItem(libraryTransfer.getItem().ItemObj, libraryTransfer.getItem().CommentObj, libraryTransfer.getItem().FileInfoObj);
                
               
            }
        }
        

        /// <summary>
        /// load the details of an item to the form
        /// </summary>
        private void loadItem()
        {
            try
            {
                Common.DataObject.Comment commentObj = item.CommentObj;
                Common.DataObject.FileInfo fileInfo = item.FileInfoObj;
                Common.DataObject.Item itemObj = item.ItemObj;

                tbSummary.Text = commentObj.Summary;
                tbPros.Text = commentObj.Pros;
                tbCons.Text = commentObj.Cons;
                if (commentObj.Tags != null)
                {
                    if (commentObj.Tags.Count != 0)
                    {
                        foreach (string tag in commentObj.Tags)
                        {
                            tbTag.Text = tbTag.Text + tag + ",";
                        }
                        tbTag.Text = tbTag.Text.Substring(0, tbTag.Text.Length - 1);
                    }

                }
                double rating = commentObj.Rating;
                rating = 5.0;
                mtbRating.Text = rating.ToString("0.0");
                if (commentObj.ReviewFile.Equals(""))
                {
                    tbReviewFile.Text = "";
                }
                else
                {
                    tbReviewFile.Text = buddy.IpAdd + "\\" + commentObj.ReviewFile;
                }
                if (fileInfo.Existence == false && fileInfo.FileName.Equals(""))
                {
                    tbFileLocation.Text = "";
                }
                else
                {
                    tbFileLocation.Text = buddy.IpAdd + "\\" + fileInfo.FileName;
                }
                lblFileSize.Text = fileInfo.Size.ToString();
                lblFileExistence.Text = fileInfo.Existence.ToString();
              
                chkBShare.Checked = !itemObj.BPrivate;
                chkBShare.Enabled = false;
                string[] itemArray = convertToStringArray(itemObj.BibTexes);
                DataTable dt = new DataTable();
                for (int i = 0; i < 9; i++)
                {
                    dt.Columns.Add();
                }
                dt.Rows.Add(itemArray);
                grdvItem.DataSource = dt;
                grdvItem.Rows[0].ReadOnly = true;
                lblCat.Text = itemObj.Category;
            }
            catch
            {

            }

        }
        
        private string[] convertToStringArray(ArrayList arlOfBibTexese)
        {
            string[] itemArray = new string[9];
            for (int i = 0; i < 9; i++)
            {
                itemArray[i] = "";
            }
            foreach (Object btStruct in arlOfBibTexese)
            {

                BibTexStruct bts = (BibTexStruct)btStruct;
                switch (bts.name)
                {
                    case "title":
                        itemArray[0] = bts.value; break;
                    case "author":
                        itemArray[1] = bts.value; break;
                    case "publisher":
                        itemArray[2] = bts.value; break;
                    case "year":
                        itemArray[3] = bts.value; break;
                    case "edition":
                        itemArray[4] = bts.value; break;
                    case "pages":
                        itemArray[5] = bts.value; break;
                    case "editor":
                        itemArray[6] = bts.value; break;
                    case "organization":
                        itemArray[7] = bts.value; break;
                    case "volume":
                        itemArray[8] = bts.value; break;
                }
            }
            return itemArray;
        }
    }
}